//
//  M4InfosProvinceView.swift
//  M4
//
//  Created by YuChuang on 2024/8/12.
//

import UIKit

class M4InfosProvinceView: UIView, UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return allNameSortKey.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let key = allNameSortKey[section]
        return sortProvinCityData[key]?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "M4ProvinceCityCell", for: indexPath) as? M4ProvinceCityCell
        let key = allNameSortKey[indexPath.section]
        cell?.data = sortProvinCityData[key]?[indexPath.row]
        cell?.M4ProvinceCityTag.isHidden = indexPath.row == 0 ? false : true
        cell?.M4ProvinceCityTag.text = key
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let key = allNameSortKey[indexPath.section]
        if currentProvince {
            M4ChooseProvin = sortProvinCityData[key]?[indexPath.row]
            M4InfosProvinLabel.text = M4ChooseProvin?.HYYXEhEZ
            M4InfosProvinLabel.textColor = COLOR_333333
            M4InfosCityLabel.isHidden = false
            M4InfosCityHeight.constant = 47
            currentProvince = false
            let cityData: [M4ProvinceCityModel] = M4ProvinCityData?.1.filter({$0.KWwseY == M4ChooseProvin?.ZySZN}) ?? []
            sortProvinCityNameList(all: cityData)
        }
        else {
            M4ChooseCity = sortProvinCityData[key]?[indexPath.row]
            M4InfosCityLabel.text = M4ChooseCity?.HYYXEhEZ
            M4InfosCityLabel.textColor = COLOR_333333
            M4PopViewHidden(subview: self.M4InfosProvinBGView)
            M4ProvinCityBlock?(M4ChooseProvin, M4ChooseCity)
        }
    }
    
    
    @IBOutlet weak var M4InfosProvinBGView: UIView!
    
    @IBOutlet weak var M4InfosProvinTitle: UILabel!
    
    @IBOutlet weak var M4InfosProvinLabel: UILabel!
    
    @IBOutlet weak var M4InfosProvinButton: UIButton!
    
    @IBOutlet weak var M4InfosCityLabel: UILabel!
    
    @IBOutlet weak var M4InfosProvinTable: UITableView!
    
    @IBOutlet weak var M4InfosCityHeight: NSLayoutConstraint!
    
    @IBOutlet weak var M4InfosProvinViewHright: NSLayoutConstraint!
    
    private var M4ProvinCityData: ([M4ProvinceCityModel], [M4ProvinceCityModel])?
    
//    private var M4Datas: [M4ProvinceCityModel]?
    
    private var allNameSortKey: [String] = []
    
    private var sortProvinCityData: [String : [M4ProvinceCityModel]] = [:]
    
    private var currentProvince: Bool = true
    
    private var M4ChooseProvin: M4ProvinceCityModel?
    
    private var M4ChooseCity: M4ProvinceCityModel?
    
    var M4ProvinCityBlock: ((M4ProvinceCityModel?, M4ProvinceCityModel?) -> Void)?
    
    override func awakeFromNib() {
        self.frame = CGRect(x: 0, y: 0, width: M4ScreenWidth, height: M4ScreenHeight)
        M4InfosProvinViewHright.constant = M4ScreenHeight/3*2
        M4InfosCityLabel.isHidden = true
        M4InfosCityHeight.constant = 0
        M4InfosProvinTable.rowHeight = UITableView.automaticDimension
        M4InfosProvinTable.estimatedRowHeight = 160
        if #available(iOS 15.0, *) {
            M4InfosProvinTable.sectionHeaderTopPadding = 0
        }
        M4InfosProvinTable.delegate = self
        M4InfosProvinTable.dataSource = self
        M4InfosProvinTable.register(UINib(nibName: "M4ProvinceCityCell", bundle: nil), forCellReuseIdentifier: "M4ProvinceCityCell")
    }
    
    @IBAction func M4InfosProvinViewClose(_ sender: UIButton) {
        self.M4PopViewHidden(subview: self.M4InfosProvinBGView)
        sender.M4EventUnavailable = false
    }
    
    @IBAction func M4InfosProvinButtonClick(_ sender: UIButton) {
        M4InfosProvinLabel.text = "Seleccione el estado"
        M4InfosProvinLabel.textColor = COLOR_00479D
        M4InfosCityLabel.isHidden = true
        M4InfosCityHeight.constant = 0
        currentProvince = true
        sortProvinCityNameList(all: M4ProvinCityData?.0 ?? [])
        sender.M4EventUnavailable = false
    }
    
    
    func M4UpdateViewUI(title: String, model: ([M4ProvinceCityModel], [M4ProvinceCityModel])) {
        M4InfosProvinTitle.text = title
        M4ProvinCityData = model
//        M4Datas = M4ProvinCityData?.0
        currentProvince = true
        sortProvinCityNameList(all: M4ProvinCityData?.0 ?? [])
        self.M4PopViewShow(subview: self.M4InfosProvinBGView)
    }

}

extension M4InfosProvinceView {
    
    func sortProvinCityNameList(all: [M4ProvinceCityModel]) {
        allNameSortKey.removeAll()
        sortProvinCityData.removeAll()
        for item in all {
            let name = item.HYYXEhEZ ?? ""
            let firstLetter = (name as NSString).substring(with: NSRange.init(location: 0, length: 1)).uppercased()
            var itemNames:[M4ProvinceCityModel] = []
            if sortProvinCityData.keys.contains(firstLetter) {
                itemNames = sortProvinCityData[firstLetter]!
                itemNames.append(item)
            } else {
                itemNames.append(item)
            }
            sortProvinCityData[firstLetter] = itemNames
        }
        allNameSortKey = sortProvinCityData.keys.sorted(by: { name1, name2 in
            return name1 < name2
        })
        M4InfosProvinTable.reloadData()
    }
    
    
}
